import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shenfuhui/config/config.dart';
import 'package:shenfuhui/entity/user_info_entity.dart';
import 'package:shenfuhui/provider/userinfo_provider.dart';
import 'package:shenfuhui/utils/user_utils.dart';
import 'package:shenfuhui/views/dialog_manager.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../http/api.dart';
import '../routers/routers.dart';

class HomeMine extends StatefulWidget {
  const HomeMine({Key? key}) : super(key: key);

  @override
  State<HomeMine> createState() => _HomeMineState();
}

class _HomeMineState extends State<HomeMine> {
  ///
  /// 资产区item
  ///
  Widget getAssetItem(IconData icon, String name, Function() onTap) {
    return Container(
      width: double.infinity,
      height: 105.w,
      padding: EdgeInsets.symmetric(vertical: 0, horizontal: 24.w),
      margin: EdgeInsets.fromLTRB(40.w, 24.w, 40.w, 0),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.w),
      ),
      child: InkWell(
        onTap: onTap,
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Icon(
                  icon,
                  size: 44.w,
                  color: Config.colorMain,
                ),
                Padding(
                  padding: EdgeInsets.only(left: 20.w),
                ),
                Text(
                  name,
                  style: TextStyle(
                      fontSize: 26.sp, height: 1.5, color: Config.colorText1),
                ),
              ],
            ),
            Text(
              "0.0000",
              style: TextStyle(
                  fontSize: 26.sp, height: 1.5, color: Config.colorText1),
            ),
          ],
        ),
      ),
    );
  }

  ///
  /// 金刚区的Item
  ///
  Widget getJingangItem(IconData icon, String name, Function() onTap) {
    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            icon,
            size: 42.w,
            color: Config.colorMain,
          ),
          Text(name,
              style: TextStyle(
                  fontSize: 21.sp, height: 1.8, color: Config.colorText1)),
        ],
      ),
    );
  }

  Widget getLoginOutView() {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    if (infoEntity.code == 0) {
      return const Padding(padding: EdgeInsets.all(0));
    } else {
      return Container(
        width: double.infinity,
        height: 98.w,
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0.w),
        margin: EdgeInsets.symmetric(vertical: 14.w, horizontal: 35.w),
        child: ElevatedButton(
          onPressed: () {
            DialogManager.showDefaultDialog(context, "确认退出登录吗", () {
              UserUtils.loginOut(context);
            });
          },
          style: ElevatedButton.styleFrom(
            primary: Config.colorMain,
            onPrimary: Config.colorBg,
            shadowColor: Config.colorBg,
            elevation: 0,
            // shape: const StadiumBorder(),
          ),
          child: const Text(
            "退出登录",
            style: TextStyle(color: Config.colorWhite),
          ),
        ),
      );
    }
  }

  ///
  /// 返回用户名的布局，登录与未登录分别返回不同的布局
  ///
  Widget showIsLogin(context) {
    UserInfoEntity infoEntity = Provider.of<UserInfoProvider>(context).userInfo;
    if (infoEntity.code == 200) {
      return Padding(
        padding: EdgeInsets.fromLTRB(25.w, 10.w, 25.w, 0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Text(
              infoEntity.user.nickname,
              style: TextStyle(color: (Config.colorText1), fontSize: 36.sp),
            ),
            Padding(
              padding: EdgeInsets.all(5.w),
            ),
            Text(
              infoEntity.user.username,
              style: TextStyle(color: (Config.colorText1), fontSize: 25.sp),
            ),
          ],
        ),
      );
    } else {
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 8.w, horizontal: 25.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            InkWell(
              onTap: () {
                // Future.delayed(const Duration(milliseconds: 1200), () {
                //   setState(() {
                //     bo = true;
                //   });
                // });
                Routes.router.navigateTo(context, Routes.login,
                    transition: TransitionType.inFromRight);
              },
              child: Text(
                '点击登录',
                style: TextStyle(color: (Config.colorText1), fontSize: 38.sp),
              ),
            ),
          ],
        ),
      );
    }
  }

  ///
  /// 请求个人中心接口
  ///
  getUserInfo(Function onSucces) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? token = prefs.getString("token");
    if (token != null) {
      dynamic users = await Api.getUserinfo();
      Map<String, dynamic> resultUsers = Map.from(users);
      UserInfoEntity infoEntity = UserInfoEntity.fromJson(resultUsers);
      onSucces(infoEntity);
    }
  }

  ///
  /// 判断头像有木有，没有就用本地的占位
  ///
  ImageProvider getHeadImage() {
    UserInfoEntity info = Provider.of<UserInfoProvider>(context).userInfo;
    if (info.code == 200 && info.user.headicon.length > 1) {
      return NetworkImage('${Config.baseUrl}${info.user.headicon}');
    } else {
      return const AssetImage('assets/images/launcher.png');
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUserInfo((UserInfoEntity infoEntity) {
      Provider.of<UserInfoProvider>(context, listen: false)
          .changeUserinfo(infoEntity);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Config.colorBg2,
        width: double.infinity,
        height: double.infinity,
        child: SingleChildScrollView(
          scrollDirection: Axis.vertical,
          child: Stack(
            children: [
              // Image.asset(
              //   'assets/images/mine_top_bg.png',
              //   width: double.infinity,
              //   height: 390.w,
              //   fit: BoxFit.fill,
              // ),
              Column(
                children: [
                  Container(
                    //头像区
                    height: 145.w,
                    margin: EdgeInsets.fromLTRB(40.w, 110.w, 0, 0),
                    child: Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        ClipOval(
                          child: Container(
                              width: 145.w,
                              height: 145.w,
                              color: (Config.colorWhite),
                              padding: EdgeInsets.all(3.w),
                              child: CircleAvatar(
                                backgroundImage: getHeadImage(),
                              )),
                        ),
                        showIsLogin(context),
                      ],
                    ),
                  ),
                  getAssetItem(Icons.monetization_on_outlined, "USDT", () {
                    Routes.navigateTo(context, Routes.assetGeneralDetail,
                        params: {'pageTitle': 'USDT'});
                  }),
                  getAssetItem(Icons.link, "陨石链", () {
                    Routes.navigateTo(context, Routes.assetGeneralDetail,
                        params: {'pageTitle': '陨石链'});
                  }),
                  getAssetItem(Icons.business_center_sharp, "总资产包", () {
                    Routes.navigateTo(
                      context,
                      Routes.assetPackge,
                    );
                  }),
                  Container(
                    //金刚区
                    width: double.infinity,
                    height: 195.w,
                    padding:
                        EdgeInsets.symmetric(vertical: 0, horizontal: 20.w),
                    margin: EdgeInsets.fromLTRB(40.w, 30.w, 40.w, 0),
                    decoration: BoxDecoration(
                      color: Colors.white,
                      borderRadius: BorderRadius.circular(12.w),
                    ),
                    child: Column(
                      children: [
                        Container(
                          margin: EdgeInsets.symmetric(
                              vertical: 20.w, horizontal: 6.w),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                '我的订单',
                                style: TextStyle(fontSize: 25.sp),
                              ),
                              Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: [
                                  InkWell(
                                    onTap: () {
                                      // if (await UserUtils.isLogin(context) == false) {
                                      //   return;
                                      // }
                                      Routes.router.navigateTo(
                                          context, Routes.orderIndex,
                                          transition:
                                              TransitionType.inFromRight);
                                    },
                                    child: Text(
                                      '查看全部',
                                      style: TextStyle(
                                          fontSize: 23.sp,
                                          color: Config.colorText3),
                                    ),
                                  ),
                                  Padding(
                                    padding: EdgeInsets.only(left: 5.w),
                                  ),
                                  Icon(
                                    Icons.arrow_forward_ios,
                                    size: 25.w,
                                    color: Config.colorText3,
                                  ),
                                ],
                              ),
                            ],
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(top: 10.w),
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            getJingangItem(Icons.payment, "待付款", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.router.navigateTo(
                                  context, Routes.orderIndex,
                                  transition: TransitionType.inFromRight);
                            }),
                            getJingangItem(Icons.send, "待发货", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.router.navigateTo(
                                  context, Routes.orderIndex,
                                  transition: TransitionType.inFromRight);
                            }),
                            getJingangItem(Icons.receipt_long, "待收货", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.router.navigateTo(
                                  context, Routes.orderIndex,
                                  transition: TransitionType.inFromRight);
                            }),
                            getJingangItem(Icons.weekend, "已完成", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.router.navigateTo(
                                  context, Routes.orderIndex,
                                  transition: TransitionType.inFromRight);
                            }),
                          ],
                        ),
                      ],
                    ),
                  ),
                  Container(
                      //中间列表区
                      width: double.infinity,
                      margin: EdgeInsets.symmetric(
                          vertical: 25.w, horizontal: 40.w),
                      decoration: BoxDecoration(
                        color: Config.colorBg,
                        borderRadius: BorderRadius.circular(12.w),
                      ),
                      child: Column(
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(
                                vertical: 20.w, horizontal: 25.w),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '更多功能',
                                  style: TextStyle(fontSize: 25.sp),
                                ),
                              ],
                            ),
                          ),
                          Padding(
                            padding: EdgeInsets.only(top: 0.w),
                          ),
                          SizedBox(
                            height: 260.w,
                            child: GridView.count(
                              padding: EdgeInsets.symmetric(
                                  vertical: 6.w, horizontal: 30.w),
                              mainAxisSpacing: 0.w,
                              physics: const NeverScrollableScrollPhysics(),
                              crossAxisSpacing: 40.w,
                              crossAxisCount: 4,
                              children: [
                                getJingangItem(
                                    Icons.collections_bookmark, "我的收藏",
                                    () async {
                                  // if (await UserUtils.isLogin(context) ==
                                  //     false) {
                                  //   return;
                                  // }
                                  Routes.router.navigateTo(
                                      context, Routes.mineCollcet,
                                      transition: TransitionType.inFromRight);
                                }),
                                getJingangItem(
                                    Icons.card_giftcard_rounded, "我的名片",
                                    () async {
                                  // if (await UserUtils.isLogin(context) ==
                                  //     false) {
                                  //   return;
                                  // }
                                  Routes.router.navigateTo(
                                      context, Routes.mineShareCard,
                                      transition: TransitionType.inFromRight);
                                }),
                                getJingangItem(Icons.group_add_outlined, "我的团队",
                                    () async {
                                  // if (await UserUtils.isLogin(context) ==
                                  //     false) {
                                  //   return;
                                  // }
                                  Routes.router.navigateTo(
                                      context, Routes.mineTeam,
                                      transition: TransitionType.inFromRight);
                                }),
                                getJingangItem(
                                    Icons.add_location_alt_outlined, "收货地址",
                                    () {
                                  Routes.router.navigateTo(
                                      context, Routes.mineAddressManager,
                                      transition: TransitionType.inFromRight);
                                }),
                                getJingangItem(
                                    Icons.settings_applications_outlined, "设置",
                                    () {
                                  Routes.router.navigateTo(
                                      context, Routes.mineSetting,
                                      transition: TransitionType.inFromRight);
                                }),
                              ],
                            ),
                          ),
                        ],
                      )),
                  getLoginOutView(),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}
